<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/9/17
 * Time: 9:21
 */

namespace app\home\controller;


use think\Db;

class Login extends Common
{
    /**
     * 账号管理
     * @return mixed
     */
    public function Account(){
        session('target_url',"http://south.xuanwumobile.com/home/Login/Account");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        //TODO:user_id
        $user_id = session('u_openid');
        $user_info = Db::table('up_u_user')->where('user_id', $user_id)->find();
        //是否绑定微信
        if(!empty($user_info['user_openid'])){
            $user_info['wx'] = 1;//已绑定
        }else{
            $user_info['wx'] = 0;
        }
        //是否绑定QQ
//        if(!empty($user_info['user_qq_token'])){
//            $user_info['qq'] = 1;//已绑定
//        }else{
//            $user_info['qq'] = 0;
//        }
        //是否绑定微博
//        if(!empty($user_info['user_wb_token'])){
//            $user_info['wb'] = 1;//已绑定
//        }else{
//            $user_info['wb'] = 0;
//        }
        $this->assign([
            'user_info' => $user_info
        ]);
        return $this->fetch();
    }
    
    /**
     * 验证手机号
     * @return mixed
     */
    public function verifyPhone(){
        session('target_url',"http://south.xuanwumobile.com/home/Login/verifyPhone");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        //TODO:user_id
        $user_id = session('u_openid');
        $user_phone = Db::table('up_u_user')
            ->field('user_phone')
            ->where('user_id', $user_id)
            ->find();
        $this->assign([
            'user_phone' => $user_phone,
        ]);
        return $this->fetch();
    }
    
    /**
     * 更换手机号，第一步发送验证码，验证手机号
     * @return string|\think\response\Json
     */
    public function ajaxPhone(){
        $phonecode = input('param.phonecode');
        $phone = input('param.phone');
        if($phonecode == ''){
            return json(['status'=>1, 'msg'=>'输入验证码']);
        }
        $res = Db::table('up_phonecode')
            ->where('phone',$phone)
            ->order('time2 desc')
            ->limit(1)
            ->find();
        //=============================================================
        if($phonecode != $res['code']){
            return json(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 901){
            return json(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json(['status'=>23,'msg'=>'验证码已使用']);
        }
        Db::table('up_phonecode')->where('id',$res['id'])->update(['status'=>1]);
        return json(['status'=>200,'msg'=>'ok']);
    }
    
    /**
     * 更换手机号，第二部绑定新手机
     * @return string
     */
    public function ajaxBandPhone(){
//        session('target_url',"http://south.xuanwumobile.com/home/Login/ajaxBandPhone");
//        $openid = $this->getOpenid();
//        $this->getUserId($openid);
        $phone = trim($_POST['phone'],' ');
        $code = trim($_POST['phonecode'],' ');
        //TODO:user_id
        $user_id = session('u_openid');
        if($phone == "" || $code == ""){
            return json(['status'=>0,'msg'=>'手机号和验证码不能为空']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json(['status'=>0,'msg'=>'已经有此手机号码用户']);
        }
        //=============================================================
        $res = Db::table('up_phonecode')
            ->where('phone',$phone)
            ->order('time2 desc')
            ->limit(1)
            ->find();
        //=============================================================
        if(empty($res)){
            return json(['status'=>0,'msg'=>'不是同一个手机号']);
        }
        if($code != $res['code']){
            return json(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 901){
            return json(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json(['status'=>23,'msg'=>'验证码已使用']);
        }
        $res2 = Db::table('up_u_user')->where('user_id',$user_id)->update(['user_phone'=>$phone]);
        if($res2){
//            $new = Db::table('up_u_user')->where('user_id',$user_id)->find();
            Db::table('up_phonecode')->where('id',$res['id'])->update(['status'=>1]);
            return json(['status'=>200,'msg'=>'更新成功']);
        }else{
            return json(['status'=>0,'msg'=>'更新失败']);
        }
    }
    
    /**
     * 绑定手机页面
     * @return mixed
     */
    public function bandPhone(){
        session('target_url',"http://south.xuanwumobile.com/home/Login/bandPhone");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return $this->fetch();
    }
    
    /**
     * 用户协议
     * @return mixed
     */
    public function xieYi(){
        session('target_url',"http://south.xuanwumobile.com/home/Login/xieYi");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        //TODO:缺少页面
        $res = Db::table('up_about_us')->select();
        $xieyi = $res[0]['user_argement'];
        $this->assign([
            'xieyi' => $xieyi,
        ]);
        return $this->fetch();
    }
    
    /**
     * 修改密码页面
     * @return mixed
     */
    public function changePwd(){
        session('target_url',"http://south.xuanwumobile.com/home/Login/changePwd");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return $this->fetch();
    }
    
    /**
     * 修改密码
     * @return \think\response\Json
     */
    public function ajaxChangePwd(){
//        session('target_url',"http://south.xuanwumobile.com/home/Login/ajaxBandPhone");
//        $openid = $this->getOpenid();
//        $this->getUserId($openid);
        $params = input('param.');
        //TODO:user_id
        $user_id = session('u_openid');
        $oldPassword = trim($params['oldPassword']);
        $newPassword = trim($params['newPassword']);
        if($oldPassword == ''){
            return json(['status'=>1, 'msg'=>'请输入旧密码']);
        }
        if($newPassword == ''){
            return json(['status'=>2, 'msg'=>'请输入新密码']);
        }
        $oldPW = Db::table('up_u_user')->where('user_id', $user_id)->find();
        if(md5($oldPassword) != $oldPW['user_password']){
            return json(['status'=>3, 'msg'=>'旧密码错误，请重新输入']);
        }
        $updatePassword['user_password'] = md5($newPassword);
        $res = Db::table('up_u_user')->where('user_id', $user_id)->update($updatePassword);
        if($res){
            return json(['status'=>200, 'msg'=>'修改成功']);
        }else{
            return json(['status'=>5, 'msg'=>'修改失败']);
        }
    }
    
    /**
     * 找回密码页面
     * @return mixed
     */
    public function getPwd(){
        session('target_url',"http://south.xuanwumobile.com/home/Login/getPwd");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return $this->fetch();
    }
    
    /**
     * 找回密码
     * @return \think\response\Json
     */
    public function ajaxGetPwd(){
        $phone = input('param.phone');
        $code = input('param.phonecode');
        $newpass = input('param.newpass');
        $type = input('param.type');
        if(!isset($phone) || !isset($code)){
            return json(['status'=>0,'msg'=>'参数错误']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($newpass == '' || $code == ''){
            return json(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')
            ->where('phone',$phone)
            ->order('time2 desc')
            ->limit(1)
            ->find();
        //=============================================================
        if($code != $res['code']){
            return json(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 901){
            return json(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json(['status'=>23,'msg'=>'验证码已使用']);
        }
        //TODO 修改密码成功后如果直接登录那么就要更新token
        $token = md5(date('YmdHis').rand(100000,999999));
        $update = array();
        $update['user_password'] = md5($newpass);
        if($type == 1){//修改后直接登录
            $update['user_token'] = $token;
        }
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update($update);
        if($res){
            Db::table('up_phonecode')->where('id',$res['id'])->update(['status'=>1]);
            return json(['status'=>200,'msg'=>'密码重置成功']);
        }else{
            return json(['status'=>3,'msg'=>'密码重置失败']);
        }
    }
    
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone：填写的手机号
     * type：   1 验证手机号   2 更换绑定的手机号
     */
    public function getPhoneCode(){
        header("Access-Control-Allow-Origin:*");
        //TODO:user_id
        $user_id = session('u_openid');
        $params = input('param.');
//        $params['phone'] = '15950506394';
        if(trim($params['phone'], ' ') == ''){
            return $this->apiError(0, '请输入手机号');
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $params['phone'])){
            return $this->apiError(1, '请输入正确格式的手机号');
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(empty($userInfo) && $params['type'] == 1){//验证手机号
            return $this->apiError(2, '没有此手机号的用户');
        }
        if(!empty($userInfo) && $params['type'] == 2){//更换绑定的手机号
            return $this->apiError(3, '此号码已被绑定');
        }
        $startTime = strtotime(date('Y-m-d 00:00:00'));//当天的起始时间
        $endTime = strtotime(date('Y-m-d 23:59:59'));//当天的结束时间
        $where = [];
        $where['phone'] = $params['phone'];
        $where['time2'] = ['between', [$startTime, $endTime]];
        $num = Db::table('up_phonecode')->where($where)->count('id');
        if($num == 5){
            return $this->apiError(10, '短信验证码今日已发送5次，请明天再来');
        }
        $code = GetRandCode();//6位数验证码
        $templateid = config('yzx')['templateid'];
        $sendres = YzxSms($templateid, $code, $params['phone'], $user_id);//发送验证码
        if($sendres['code'] != '00000'){//发送不成功
            return json(['status'=>11,'msg'=>$sendres['msg']]);
        }else{
            $data = [
                'phone' => $params['phone'],//发送的手机号
                'code' => $code,//加密后的验证码
                'time2' => time(),//验证码发送的时间戳
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res){
                return json(['status' => 12, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }
    
    /**
     * 用户协议
     */
    public function userArgement(){
        session('target_url',"http://south.xuanwumobile.com/home/Login/userArgement");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $user_argement = Db::table('up_about_us')->where('id', 1)->value('user_argement');
        $this->assign([
            'user_agrement' => $user_argement
        ]);
        return $this->fetch();
    }
}